package com.seeyon.apps.kk.manager.meetingImpl;

import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jersey.repackaged.com.google.common.collect.Lists;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.seeyon.apps.kk.manager.BaseManager;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.apps.meeting.manager.MeetingManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.kk.model.SqlAndParam;
import com.seeyon.kk.utils.CoreUtils;
import com.seeyon.kk.utils.ValueUtils;
import com.seeyon.v3x.meeting.domain.MtMeeting;

public class ShkkMeetingManagerImpl extends BaseManager {
	private static final Log log = LogFactory.getLog(ShkkMeetingManagerImpl.class);
	private FreemarkFlowManager freemarkFlowManager;
	private String id;
	private String title;
	private String ok;
	private String oaFileSaveUrl;

	public String getOaFileSaveUrl() {
		return oaFileSaveUrl;
	}

	public void setOaFileSaveUrl(String oaFileSaveUrl) {
		this.oaFileSaveUrl = oaFileSaveUrl;
	}

	public String getOk() {
		return ok;
	}

	public void setOk(String ok) {
		this.ok = ok;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	// 新建会议
	public boolean createNewMeeting(String meetingId, String meetingRoomPermId, String description) {
		boolean flagResult = true;
		// 会议信息
		MeetingManager meetingManager = (MeetingManager) AppContext.getBean("meetingManager");
		MtMeeting meetingInfo = null;
		// 组织管理
		OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
		// 获取文件
		try {
			meetingInfo = meetingManager.getMeetingById(Long.valueOf(meetingId));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("===========SHKK=========TMSD（天目神盾）CREATE_MEETING======================《" + meetingInfo.getTitle()
				+ "》");
		log.info("===========SHKK=========TMSD（天目神盾）meetingInfo:"+meetingInfo);
		// 会议基本信息
		Map<String, Object> meetingInfoMap = Maps.newHashMap();
		meetingInfoMap.put("meetingId", meetingInfo.getId());
		meetingInfoMap.put("roomId", meetingInfo.getRoom());// roomId
		meetingInfoMap.put("name", meetingInfo.getTitle()); // 会议标题
		meetingInfoMap.put("content",
				meetingInfo.getContent() == null ? null
						: meetingInfo.getContent().replace("<p>", "").replace("<strong>", "").replace("</strong>", "")
								.replace("</p>", ""));
		log.info("===========SHKK=========TMSD（天目神盾）"+meetingInfo.getContent());
		meetingInfoMap.put("deptId", null); // 承办部门的部门ID（非必填项）
		meetingInfoMap.put("startTimeExpect", meetingInfo.getBeginDate());
		meetingInfoMap.put("endTimeEx", meetingInfo.getEndDate());
		meetingInfoMap.put("secretLevel", meetingInfo.getMeetingType());// 会议密级
																		// （0：公开-->1：内部-->2:秘密-->3:机密）
		try {
			meetingInfoMap.put("creater", orgManager.getMemberById(meetingInfo.getCreateUser()).getLoginName()); // 会议创建人的登录名
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		meetingInfoMap.put("createTime", meetingInfo.getCreateDate());
		meetingInfoMap.put("checkApplyTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")); // 会议审批通过时间
		try {
			meetingInfoMap.put("linkMan", orgManager.getMemberById(meetingInfo.getCreateUser()).getName()); // 联系人的姓名，负责在会议系统客户端开启会议。
		} catch (BusinessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		meetingInfoMap.put("linkManId", meetingInfo.getCreateUser()); // 联系人ID
		meetingInfoMap.put("agendaSecretLevel", ""); // 没有会议议程、不必填写。
		meetingInfoMap.put("note", meetingInfo.getNotice()); // 备注说明（非必填）

		// 审批信息（OA中只需审批一次，没有层级）
		Map<String, Object> checkInfoMap = Maps.newHashMap();
		checkInfoMap.put("id", meetingRoomPermId); // 会议室审批信息的ID
		checkInfoMap.put("oaMeetingId", meetingInfo.getId());
		checkInfoMap.put("loginName", AppContext.getCurrentUser().getLoginName());// 获取当前审批人的登录名
		checkInfoMap.put("userName", AppContext.getCurrentUser().getName());// 获取当前审批人的姓名
		checkInfoMap.put("action", "一级审批同意");// 能到这里的都是审批通过的
		checkInfoMap.put("checkTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		checkInfoMap.put("checkInfo", description);// 审批、批示内容、建议必须有。

		// 与会人员信息
		List<Map<String, Object>> personInfoList = Lists.newArrayList();
		Set<V3xOrgMember> membersInScope = null;
		try {
			membersInScope = orgManager.getMembersByTypeAndIds(meetingInfo.getConferees());
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Set<Long> memberIdsInScope = new HashSet<Long>();
		if (membersInScope != null && membersInScope.size() > 0) {
			for (V3xOrgMember member : membersInScope) {
				if (member.isValid() && !member.getIsDeleted().booleanValue() && member.getIsInternal()) {
					memberIdsInScope.add(member.getId());
				}
			}
		}

		meetingInfoMap.put("maxTid", memberIdsInScope.size());// 参加会议的人数

		for (Iterator iterator = memberIdsInScope.iterator(); iterator.hasNext();) {
			Map<String, Object> personInfoMap = Maps.newHashMap();
			Long memberId = (Long) iterator.next();
			Map<String, Object> paramMap = Maps.newHashMap();
			paramMap.put("memberId", memberId);
			// 循环通过人员ID获取信息
			personInfoMap.put("id", memberId); // 参会人员ID
			personInfoMap.put("oaMeetingId", meetingInfo.getId()); // 会议ID
			personInfoMap.put("pos", ""); // 参会人员的座位号===============================约定OA不用传任何东西=======================================================>>
			personInfoMap.put("userType", 1); // 人员类型： 1、本单位 3、外来参会人员(固定给1)
			try {
				personInfoMap.put("loginName", orgManager.getMemberById(memberId).getLoginName());// 获取每个人的登录名
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			SqlAndParam sapTwo = this.ibatisQueryDao.getSqlAndParametersFromIbatis("findPwdStrengthIdByMemberId.select",
					paramMap);// 获取人员密级信息
			List<Map<String, Object>> vlTwo = this.jdbcTemplate.queryForList(sapTwo.getSql(), sapTwo.getValues());
			int pwd_strengthValue = 0;
			if (vlTwo.get(0).get("pwd_strength") != null) {
				pwd_strengthValue = Integer.parseInt(vlTwo.get(0).get("pwd_strength").toString());
				if (pwd_strengthValue == 1) {
					pwd_strengthValue = 2;
				} else if (pwd_strengthValue == 2) {
					pwd_strengthValue = 3;
				} else if (pwd_strengthValue == 3) {
					pwd_strengthValue = 4;
				}
			}
			personInfoMap.put("secretLevel", pwd_strengthValue);// 人员涉密等级
			try {
				personInfoMap.put("name", orgManager.getMemberById(memberId).getName());// 姓名
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			personInfoMap.put("post", null);// 职务非必须、默认不传。
			String path = "";
			String unitName = "";
			// 通过memberId查询部门全称
			try {
				Long departmentId = orgManager.getMemberById(memberId).getOrgDepartmentId();
				path = orgManager.getUnitById(departmentId).getPath();
				// 根据path拼接部门全称
				for (int i = path.length() / 4 - 2; i >= 0; i--) {
					List<Map<String, Object>> vlThree = this.jdbcTemplate.queryForList(
							"select*from ORG_UNIT where path=" + path.substring(0, path.length() - (i * 4)));
					unitName += vlThree.get(0).get("name") + "/";
				}
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			personInfoMap.put("unit", unitName.substring(0, unitName.length() - 1));
			personInfoList.add(personInfoMap);
		}

		// 会议资料信息
		List<Map<String, Object>> meetingFileList = Lists.newArrayList();
		// 调用系统本身接口获取附件信息
		String token = CoreUtils.doGet(ValueUtils.getConfig().getString("shkk.getOAsystemToken"), null, "utf-8", false);
		if (token.startsWith("{")) {
			JSONObject tokenJson = JSONObject.parseObject(token);
			token = tokenJson.getString("id");
		}
		String getResult = CoreUtils.doGet(ValueUtils.getConfig().getString("shkk.OAmeetingInterfaceAddress")
				+ meetingInfo.getId() + "?token=" + token, null, "utf-8", false);
		if (!getResult.isEmpty()) {
			JSONObject getJsonResult = (JSONObject) JSON.parseObject(getResult).get("extraMap");// 获取附件相关信息
			if (getJsonResult != null) {
				JSONArray getJsonArray = getJsonResult.getJSONArray("atts");
				for (int i = 0; i < getJsonArray.size(); i++) {
					JSONObject jsonSon = (JSONObject) getJsonArray.get(i);
					Map<String, Object> meetingFileMap = Maps.newHashMap();
					meetingFileMap.put("oaFileId", jsonSon.get("id"));
					meetingFileMap.put("oaMeetingId", meetingInfo.getId());
					meetingFileMap.put("pos", i);// 文件的排序（1、2、3、4）
					meetingFileMap.put("name", jsonSon.get("filename"));
					meetingFileMap.put("fileSize", jsonSon.get("size"));
					meetingFileMap.put("fileType", "." + jsonSon.get("extension"));
					String fileType = meetingFileMap.get("name").toString().substring(0, 4);
					int fileTypeValue = 0;// 默认为不涉密文件
					if (fileType.contains("内部")) {
						fileTypeValue = 1;
					} else if (fileType.contains("秘密")) {
						fileTypeValue = 2;
					} else if (fileType.contains("机密")) {
						fileTypeValue = 3;
					}
					meetingFileMap.put("secretLevel", fileTypeValue); // 根据附件名称区分是哪种类型的文件（1.非密
																		// 2.内部
																		// 3.秘密
																		// 4.机密）
					meetingFileMap.put("createTime", meetingInfo.getCreateDate());// 会议创建的时候上传了附件
					meetingFileMap.put("deleteMark", "");// 附件是否删除标识
					meetingFileMap.put("fileUrl", jsonSon.get("fileUrl"));// 存储在OA服务器的附件名称
					meetingFileList.add(meetingFileMap);
				}
			}
		} else {
			log.info("===========SHKK=========TMSD（天目神盾）CREATE_MEETING======================《" + meetingInfo.getTitle()
					+ "》，没有附件！");
		}

		Map<String, Object> allInfoMap = Maps.newHashMap();
		allInfoMap.put("meetingInfoMap", meetingInfoMap);
		allInfoMap.put("checkInfoMap", checkInfoMap);
		allInfoMap.put("personInfoList", personInfoList);
		allInfoMap.put("meetingFileList", meetingFileList);

		String meetingInfoFtl = this.freemarkFlowManager.fltTemplateIntoString("aboutMeeting/PostMeetingVal.ftl",
				allInfoMap);
		String meetingSystemInterfaceUrl = ValueUtils.getConfig().getString("shkk.TMSDcreateMeetingUrl");
		Map<String, Object> headParams = Maps.newHashMap();
		headParams.put("ContentType", "application/json");
		headParams.put("token", "token");
		String createMeetingresult = CoreUtils.doPost(meetingSystemInterfaceUrl, headParams, meetingInfoFtl, "UTF-8",
				true);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (createMeetingresult != null && !createMeetingresult.isEmpty()) {
			// 会议创建成功、传送附件到会议系统(传送附件的方式使用http，并且上传附件的路径依赖于创建会议返回的信息。)
			JSONObject createMeetingresultJson = JSON.parseObject(createMeetingresult);
			if (createMeetingresultJson.getBooleanValue("result")) {
				String currentYear = DateFormatUtils.format(new Date(), "yyyy");
				String currentMonth = DateFormatUtils.format(new Date(), "MM");
				String currentDay = DateFormatUtils.format(new Date(), "dd");
				String datePath = currentYear + File.separator + currentMonth + File.separator + currentDay
						+ File.separator;
				// 获取返回消息，根据回传的文件内容上传文档。
				JSONArray jsonArray = (JSONArray) createMeetingresultJson.get("meetingFilePathList");
				if (jsonArray != null) {
					// 传输文件资料
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject json = (JSONObject) jsonArray.get(i);
						String contentPath = json.get("content").toString();
						String meetingFileUrl = ValueUtils.getConfig().getString("shkk.TMSDmeetingFileUrl");
						String fileName = meetingFileList.get(i).get("fileUrl").toString();
						// 还要查询出要传输的文件所在位置
						try {
							String postResult = "false";
							String postFileResult = CoreUtils.HPupload(oaFileSaveUrl + datePath + fileName,
									meetingFileUrl, contentPath);
							if (postFileResult != null) {
								JSONObject postFileResultJson = JSON.parseObject(postFileResult);
								postResult = postFileResultJson.getString("result");
							}
							if (postResult.equals(ok)) {
								log.info("===========SHKK=========TMSD（天目神盾）POST_FILE=========SUCCESS===========传输文件《"
										+ meetingFileList.get(i).get("name") + "》成功!");
							} else {
								log.info("===========SHKK=========TMSD（天目神盾）POST_FILE=====================传输文件《"
										+ meetingFileList.get(i).get("name") + "》失败!请求结果：" + postFileResult);
							}
						} catch (Exception e) {
							log.info("===========SHKK=========TMSD（天目神盾）POST_FILE=====================传输文件《"
									+ meetingFileList.get(i).get("name") + "》失败!异常信息：" + e);
						}
					}
				}
			} else {
				log.info("===========SHKK=========TMSD（天目神盾）CREATE_MEETING=====================创建会议失败!返回消息："
						+ createMeetingresult);
			}
		} else {
			flagResult = false;
			log.info("===========SHKK=========TMSD（天目神盾）CREATE_MEETING=====================创建会议失败!请求结果："
					+ createMeetingresult);
		}
		return flagResult;
	}

	// 修改会议信息
	public boolean updateMeeting(String meetingId, String meetingRoomPermId, String description) {
		boolean flagResult = true;
		// 会议信息
		MeetingManager meetingManager = (MeetingManager) AppContext.getBean("meetingManager");
		MtMeeting meetingInfo = null;
		// 组织管理
		OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
		// 获取文件
		try {
			// 延迟3秒请求，让数据入库
			Thread.sleep(3000);
			meetingInfo = meetingManager.getMeetingById(Long.valueOf(meetingId));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("===========SHKK=========TMSD（天目神盾）UPDATE_MEETING======================《" + meetingInfo.getTitle()
				+ "》");
		// 会议基本信息
		Map<String, Object> meetingInfoMap = Maps.newHashMap();
		meetingInfoMap.put("meetingId", meetingInfo.getId());
		meetingInfoMap.put("roomId", meetingInfo.getRoom());// roomId
		meetingInfoMap.put("name", meetingInfo.getTitle()); // 会议标题
		// 防止出现错误信息
		String content = meetingInfo.getContent() == null ? null
				: meetingInfo.getContent().replace("<p>", "").replace("<strong>", "").replace("</strong>", "")
				.replace("</p>", "");
		log.info("=====shkk 会议内容："+content);
		meetingInfoMap.put("content", content); 
		meetingInfoMap.put("deptId", null); // 承办部门的部门ID（非必填项）
		meetingInfoMap.put("startTimeExpect", meetingInfo.getBeginDate());
		meetingInfoMap.put("endTimeEx", meetingInfo.getEndDate());
		meetingInfoMap.put("secretLevel", meetingInfo.getMeetingType());// 会议密级
																		// （0：公开-->1：内部-->2:秘密-->3:机密）
		try {
			meetingInfoMap.put("creater", orgManager.getMemberById(meetingInfo.getCreateUser()).getLoginName()); // 会议创建人的登录名
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		meetingInfoMap.put("createTime", meetingInfo.getCreateDate());
		meetingInfoMap.put("checkApplyTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")); // 会议审批通过时间
		try {
			meetingInfoMap.put("linkMan", orgManager.getMemberById(meetingInfo.getCreateUser()).getName()); // 联系人的姓名，负责在会议系统客户端开启会议。
		} catch (BusinessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		meetingInfoMap.put("linkManId", meetingInfo.getCreateUser()); // 联系人ID
		meetingInfoMap.put("agendaSecretLevel", ""); // 没有会议议程、不必填写。
		meetingInfoMap.put("note", meetingInfo.getNotice()); // 备注说明（非必填）

		meetingInfo.getRoom();

		// 审批信息（OA中只需审批一次，没有层级）
		Map<String, Object> checkInfoMap = Maps.newHashMap();
		if (meetingRoomPermId == null || meetingRoomPermId.isEmpty()) {// 如果没有修改会议室，无需再审批，即没有审批信息
			checkInfoMap.put("id", ""); // 会议室审批信息的ID
			checkInfoMap.put("oaMeetingId", "");
			checkInfoMap.put("loginName", "");// 获取当前审批人的登录名
			checkInfoMap.put("userName", "");// 获取当前审批人的姓名
			checkInfoMap.put("action", "");// 能到这里的都是审批通过的
			checkInfoMap.put("checkTime", "");
			checkInfoMap.put("checkInfo", "");// 审批、批示内容、建议必须有。
		} else {
			checkInfoMap.put("id", meetingRoomPermId); // 会议室审批信息的ID
			checkInfoMap.put("oaMeetingId", meetingInfo.getId());
			checkInfoMap.put("loginName", AppContext.getCurrentUser().getLoginName());// 获取当前审批人的登录名
			checkInfoMap.put("userName", AppContext.getCurrentUser().getName());// 获取当前审批人的姓名
			checkInfoMap.put("action", "一级审批同意");// 能到这里的都是审批通过的
			checkInfoMap.put("checkTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
			checkInfoMap.put("checkInfo", description);// 审批、批示内容、建议必须有。
		}
		// 与会人员信息
		List<Map<String, Object>> personInfoList = Lists.newArrayList();
		Set<V3xOrgMember> membersInScope = null;
		try {
			membersInScope = orgManager.getMembersByTypeAndIds(meetingInfo.getConferees());
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Set<Long> memberIdsInScope = new HashSet<Long>();
		if (membersInScope != null && membersInScope.size() > 0) {
			for (V3xOrgMember member : membersInScope) {
				if (member.isValid() && !member.getIsDeleted().booleanValue() && member.getIsInternal()) {
					memberIdsInScope.add(member.getId());
				}
			}
		}
		meetingInfoMap.put("maxTid", memberIdsInScope.size());// 参加会议的人数

		for (Iterator iterator = memberIdsInScope.iterator(); iterator.hasNext();) {
			Map<String, Object> personInfoMap = Maps.newHashMap();
			Long memberId = (Long) iterator.next();
			Map<String, Object> paramMap = Maps.newHashMap();
			paramMap.put("memberId", memberId);
			// 循环通过人员ID获取信息
			personInfoMap.put("id", memberId); // 参会人员ID
			personInfoMap.put("oaMeetingId", meetingInfo.getId()); // 会议ID
			personInfoMap.put("pos", ""); // 参会人员的座位号===============================约定OA不用传任何东西=======================================================>>
			personInfoMap.put("userType", 1); // 人员类型： 1、本单位 3、外来参会人员(固定给1)
			try {
				personInfoMap.put("loginName", orgManager.getMemberById(memberId).getLoginName());// 获取每个人的登录名
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			SqlAndParam sapTwo = this.ibatisQueryDao.getSqlAndParametersFromIbatis("findPwdStrengthIdByMemberId.select",
					paramMap);// 获取人员密级信息
			List<Map<String, Object>> vlTwo = this.jdbcTemplate.queryForList(sapTwo.getSql(), sapTwo.getValues());
			int pwd_strengthValue = 0;
			if (vlTwo.get(0).get("pwd_strength") != null) {
				pwd_strengthValue = Integer.parseInt(vlTwo.get(0).get("pwd_strength").toString());
				if (pwd_strengthValue == 1) {
					pwd_strengthValue = 2;
				} else if (pwd_strengthValue == 2) {
					pwd_strengthValue = 3;
				} else if (pwd_strengthValue == 3) {
					pwd_strengthValue = 4;
				}
			}
			personInfoMap.put("secretLevel", pwd_strengthValue);// 人员涉密等级
			try {
				personInfoMap.put("name", orgManager.getMemberById(memberId).getName());// 姓名
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			personInfoMap.put("post", null);// 职务非必须、默认不传。
			String path = "";
			String unitName = "";
			// 通过memberId查询部门全称
			try {
				Long departmentId = orgManager.getMemberById(memberId).getOrgDepartmentId();
				path = orgManager.getUnitById(departmentId).getPath();
				// 根据path拼接部门全称
				for (int i = path.length() / 4 - 2; i >= 0; i--) {
					List<Map<String, Object>> vlThree = this.jdbcTemplate.queryForList(
							"select*from ORG_UNIT where path=" + path.substring(0, path.length() - (i * 4)));
					unitName += vlThree.get(0).get("name") + "/";
				}
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			personInfoMap.put("unit", unitName.substring(0, unitName.length() - 1));
			personInfoList.add(personInfoMap);
		}

		// 会议资料信息
		List<Map<String, Object>> meetingFileList = Lists.newArrayList();
		// 调用系统本身接口获取附件信息
		String token = CoreUtils.doGet(ValueUtils.getConfig().getString("shkk.getOAsystemToken"), null, "utf-8", false);
		if (token.startsWith("{")) {
			JSONObject tokenJson = JSONObject.parseObject(token);
			token = tokenJson.getString("id");
		}
		String getResult = CoreUtils.doGet(ValueUtils.getConfig().getString("shkk.OAmeetingInterfaceAddress")
				+ meetingInfo.getId() + "?token=" + token, null, "utf-8", false);
		if (!getResult.isEmpty()) {
			JSONObject getJsonResult = (JSONObject) JSON.parseObject(getResult).get("extraMap");// 获取附件相关信息
			if (getJsonResult != null) {
				JSONArray getJsonArray = getJsonResult.getJSONArray("atts");
				for (int i = 0; i < getJsonArray.size(); i++) {
					JSONObject jsonSon = (JSONObject) getJsonArray.get(i);
					Map<String, Object> meetingFileMap = Maps.newHashMap();
					meetingFileMap.put("oaFileId", jsonSon.get("id"));
					meetingFileMap.put("oaMeetingId", meetingInfo.getId());
					meetingFileMap.put("pos", i);// 文件的排序（1、2、3、4）
					meetingFileMap.put("name", jsonSon.get("filename"));
					meetingFileMap.put("fileSize", jsonSon.get("size"));
					meetingFileMap.put("fileType", "." + jsonSon.get("extension"));
					String fileType = meetingFileMap.get("name").toString().substring(0, 4);
					int fileTypeValue = 0;// 默认为不涉密文件
					if (fileType.contains("内部")) {
						fileTypeValue = 1;
					} else if (fileType.contains("秘密")) {
						fileTypeValue = 2;
					} else if (fileType.contains("机密")) {
						fileTypeValue = 3;
					}
					meetingFileMap.put("secretLevel", fileTypeValue); // 根据附件名称区分是哪种类型的文件（1.非密
																		// 2.内部
																		// 3.秘密
																		// 4.机密）
					meetingFileMap.put("createTime", meetingInfo.getCreateDate());// 会议创建的时候上传了附件
					meetingFileMap.put("deleteMark", "");// 附件是否删除标识
					meetingFileMap.put("fileUrl", jsonSon.get("fileUrl"));// 存储在OA服务器的附件名称
					meetingFileList.add(meetingFileMap);
				}
			}
		} else {
			log.info("===========SHKK=========TMSD（天目神盾）UPDATE_MEETING======================《" + meetingInfo.getTitle()
					+ "》，没有附件！");
		}

		Map<String, Object> allInfoMap = Maps.newHashMap();
		allInfoMap.put("meetingInfoMap", meetingInfoMap);
		allInfoMap.put("checkInfoMap", checkInfoMap);
		allInfoMap.put("personInfoList", personInfoList);
		allInfoMap.put("meetingFileList", meetingFileList);

		String meetingInfoFtl = this.freemarkFlowManager.fltTemplateIntoString("aboutMeeting/PostMeetingVal.ftl",
				allInfoMap);
		String meetingSystemInterfaceUrl = ValueUtils.getConfig().getString("shkk.TMSDupdateMeetingUrl");
		Map<String, Object> headParams = Maps.newHashMap();
		headParams.put("ContentType", "application/json");
		headParams.put("token", "token");
		String createMeetingresult = CoreUtils.doPost(meetingSystemInterfaceUrl, headParams, meetingInfoFtl, "UTF-8",
				true);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if (createMeetingresult != null && !createMeetingresult.isEmpty()) {
			// 会议创建成功、传送附件到会议系统(传送附件的方式使用http，并且上传附件的路径依赖于创建会议返回的信息。)
			JSONObject createMeetingresultJson = JSON.parseObject(createMeetingresult);
			if (createMeetingresultJson.getBooleanValue("result")) {
				String currentYear = DateFormatUtils.format(new Date(), "yyyy");
				String currentMonth = DateFormatUtils.format(new Date(), "MM");
				String currentDay = DateFormatUtils.format(new Date(), "dd");
				String datePath = currentYear + File.separator + currentMonth + File.separator + currentDay
						+ File.separator;
				// 获取返回消息，根据回传的文件内容上传文档。
				JSONArray jsonArray = (JSONArray) createMeetingresultJson.get("meetingFilePathList");
				if (jsonArray != null) {
					// 传输文件资料
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject json = (JSONObject) jsonArray.get(i);
						String contentPath = json.get("content").toString();
						String meetingFileUrl = ValueUtils.getConfig().getString("shkk.TMSDmeetingFileUrl");
						String fileName = meetingFileList.get(i).get("fileUrl").toString();
						// 还要查询出要传输的文件所在位置
						try {
							String postResult = "false";
							String postFileResult = CoreUtils.HPupload(oaFileSaveUrl + datePath + fileName,
									meetingFileUrl, contentPath);
							if (postFileResult != null) {
								JSONObject postFileResultJson = JSON.parseObject(postFileResult);
								postResult = postFileResultJson.getString("result");
							}
							if (postResult.equals(ok)) {
								log.info("===========SHKK=========TMSD（天目神盾）POST_FILE=========SUCCESS===========传输文件《"
										+ meetingFileList.get(i).get("name") + "》成功!");
							} else {
								log.info("===========SHKK=========TMSD（天目神盾）POST_FILE=====================传输文件《"
										+ meetingFileList.get(i).get("name") + "》失败!请求结果：" + postFileResult);
							}
						} catch (Exception e) {
							log.info("===========SHKK=========TMSD（天目神盾）POST_FILE=====================传输文件《"
									+ meetingFileList.get(i).get("name") + "》失败!异常信息：" + e);
						}
					}
				}
			} else {
				log.info("===========SHKK=========TMSD（天目神盾）UPDATE_MEETING=====================修改会议失败!返回消息："
						+ createMeetingresult);
			}
		} else {
			flagResult = false;
			log.info("===========SHKK=========TMSD（天目神盾）UPDATE_MEETING=====================修改会议失败!请求结果："
					+ createMeetingresult);
		}
		return flagResult;
	}

	// 撤销会议
	public int revokeMeeting(String meetingId) {
		int resultflag = 0;// 天目神盾会议系统不存在此会议，OA撤销功能正常使用。
		String revokeMeetingInterfaceUrl = ValueUtils.getConfig().getString("shkk.TMSDrevokeMeetingUrl");
		Map<String, Object> postHeadMap = Maps.newHashMap();
		postHeadMap.put("ConcentType", "application/json");
		postHeadMap.put("token", "token");
		String resultStr = CoreUtils.doPost(revokeMeetingInterfaceUrl, postHeadMap, meetingId, "UTF-8", true);
		if (resultStr != null && !resultStr.isEmpty()) {
			JSONObject jsonResult = JSON.parseObject(resultStr);
			resultflag = Integer.parseInt(jsonResult.get("result").toString());
			if (resultflag == 2) {
				log.info("===========SHKK=========TMSD（天目神盾）REVOKE_MEETING=====================撤销会议失败!请求结果："
						+ jsonResult.get("errmsg"));
			} else if (resultflag == 0) {
				log.info("===========SHKK=========TMSD（天目神盾）REVOKE_MEETING=====================不存在此会议!无需撤销。");
			}
		} else {
			log.info("===========SHKK=========TMSD（天目神盾）REVOKE_MEETING=====================撤销会议失败!请求结果：" + resultStr);
		}
		return resultflag;
	}

	// 清除服务器的附件信息、保留一些基本信息。
	public boolean closeMeeting(String meetingId) {
		boolean resultflag = true;
		String closeMeetingInterfaceUrl = ValueUtils.getConfig().getString("shkk.TMSDcloseMeetingUrl");
		Map<String, Object> postHeadMap = Maps.newHashMap();
		postHeadMap.put("ConcentType", "application/json");
		postHeadMap.put("token", "token");
		String resultStr = CoreUtils.doPost(closeMeetingInterfaceUrl, postHeadMap, meetingId, "UTF-8", true);
		if (resultStr != null && !resultStr.isEmpty()) {
			JSONObject jsonResult = JSON.parseObject(resultStr);
			boolean flag = jsonResult.getBooleanValue("result");
			if (!flag) {
				resultflag = flag;
				log.info("===========SHKK=========TMSD（天目神盾）CLOSE_MEETING=====================关闭会议失败!请求结果："
						+ jsonResult.get("errmsg"));
			}
		} else {
			log.info("===========SHKK=========TMSD（天目神盾）CLOSE_MEETING=====================关闭会议失败!请求结果：" + resultStr);
		}
		return resultflag;
	}

	// 判断审批的会议是修改还是新建
	public int meetingIsCreateOrUpdate(String meetingId) {
		Map<String, Object> paramMap = Maps.newHashMap();
		paramMap.put("meetingId", meetingId);
		SqlAndParam sap = this.ibatisQueryDao.getSqlAndParametersFromIbatis("findMeetingIsCreateOrUpdate.select",
				paramMap);
		List<Map<String, Object>> vl = this.jdbcTemplate.queryForList(sap.getSql(), sap.getValues());
		int num = 1;
		if (!vl.isEmpty()) {
			num = Integer.parseInt(vl.get(0).get("num").toString());
		}
		return num;
	}
}
